# -*- coding: utf-8 -*
from flask import request, jsonify
from flask_login import login_required

from conf.flask_ini import FlaskIni
from conf.my_log import MyLog
from medical_kg.entity_type import EntityType, entity_model
from medical_kg.icd_kg import IcdKg
from medical_kg.med_kg import MedKg
from web.const import StatusCode
from web.const import CONTEXT
from web.validation import valid

app = FlaskIni().get_app()
rbac = FlaskIni().get_rbac()
med_kg_app = MedKg()
icd_kg_app = IcdKg()
entity_type_app = EntityType()

logger = MyLog().get_logger()

prefix = f'{CONTEXT}/icd_kg'


@app.route(f'{prefix}/find_child', methods=['POST'])
@rbac.allow(roles=['小萌新'], methods=['POST'])
@login_required
def find_child():
    try:
        uid = request.json['uid']
        label = request.json['label']
        label = 'ICD11' if label == '' else entity_model(label)

        valid(uid, label)

        child = icd_kg_app.find_child(uid, label)
        for ch in child:
            if ch['child'] is None or len(ch['child']) == 0:
                ch['leaf'] = True
            else:
                ch['leaf'] = False
        return jsonify({'status': StatusCode.SUCCESS_CODE, 'message': '', 'payload': child})
    except:
        raise


@app.route(f'{prefix}/fuzzy_search', methods=['POST'])
@rbac.allow(roles=['小萌新'], methods=['POST'])
@login_required
def fuzzy_search():
    try:
        index_term = request.json['index_term']
        label = request.json['label']

        valid(index_term, label)

        if len(index_term) < 2:
            return jsonify(
                {'status': StatusCode.FAILURE_CODE, 'message': 'Please pass in at least two characters', 'payload': ''})
        results = icd_kg_app.fuzzy_search(index_term, entity_model(label))
        return jsonify({'status': StatusCode.SUCCESS_CODE, 'message': '', 'payload': results})
    except:
        return jsonify({'status': StatusCode.FAILURE_CODE, 'message': 'something wrong', 'payload': ''})


@app.route(f'{prefix}/find_parent', methods=['POST'])
@rbac.allow(roles=['小萌新'], methods=['POST'])
@login_required
def find_parent():
    try:
        uid = request.json['uid']

        valid(uid)

        queue = icd_kg_app.find_parent(uid)
        return jsonify({'status': StatusCode.SUCCESS_CODE, 'message': '', 'payload': {'queue': queue}})
    except:
        return jsonify({'status': StatusCode.FAILURE_CODE, 'message': 'something wrong', 'payload': ''})


@app.route(f'{prefix}/query_disease_kg', methods=['POST'])
@rbac.allow(roles=['小萌新'], methods=['POST'])
@login_required
def query_disease_kg():
    try:
        uid = request.json['uid']

        valid(uid)

        rel_type_list = request.json['rel_type_list']
        data = MedKg().query_disease_kg(uid, rel_type_list)
        return jsonify({'status': StatusCode.SUCCESS_CODE,
                        'message': '',
                        'payload': {'results': [{'columns': [], 'data': [data]}]}})
    except:
        raise EnvironmentError


@app.route(f'{prefix}/query_rel_by_uid', methods=['POST'])
@rbac.allow(roles=['小萌新'], methods=['POST'])
@login_required
def query_rel_by_uid():
    try:
        uid = request.json['uid']

        valid(uid)

        rel_list = med_kg_app.query_rel_by_uid(uid)
        return jsonify({'status': StatusCode.SUCCESS_CODE, 'message': '', 'payload': {'rel_list': rel_list}})
    except:
        return jsonify({'status': StatusCode.FAILURE_CODE, 'message': 'something wrong', 'payload': ''})


@app.route(f'{prefix}/query_next_nodes', methods=['POST'])
@rbac.allow(roles=['小萌新'], methods=['POST'])
@login_required
def query_next_nodes():
    try:
        uid = request.json['uid']
        rel = request.json['rel']

        valid(uid, rel)

        node_list = med_kg_app.query_next_nodes(uid, rel)
        return jsonify({'status': StatusCode.SUCCESS_CODE, 'message': '', 'payload': {'node_list': node_list}})
    except:
        return jsonify({'status': StatusCode.FAILURE_CODE, 'message': 'something wrong', 'payload': ''})


@app.route(f'{prefix}/query_property', methods=['POST'])
@rbac.allow(roles=['小萌新'], methods=['POST'])
@login_required
def query_property():
    try:
        uid = request.json['uid']
        type = request.json['type']

        valid(uid, type)

        data = med_kg_app.query_property(uid, type)
        return jsonify({'status': StatusCode.SUCCESS_CODE, 'message': '', 'payload': data})
    except:
        return jsonify({'status': StatusCode.FAILURE_CODE, 'message': 'something wrong', 'payload': ''})


@app.route(f'{prefix}/query_entity_type', methods=['POST'])
@rbac.allow(roles=['小萌新'], methods=['POST'])
@login_required
def query_entity_type():
    try:
        entity_type_list = entity_type_app.query_entity_type()
        return jsonify({'status': StatusCode.SUCCESS_CODE,
                        'message': '',
                        'payload': {'entity_type_list': entity_type_list}})
    except:
        return jsonify({'status': StatusCode.FAILURE_CODE, 'message': 'something wrong', 'payload': ''})
